<template>
  <div class="hero-detail">
    <!-- 英雄大图背景 -->
    <div class="hero-background" :style="backgroundStyle"></div>
    
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <el-icon><ArrowLeft /></el-icon>
      返回
    </div>
    
    <!-- 英雄内容 -->
    <div class="hero-content">
      <div class="hero-main">
        <div class="hero-image">
          <img 
            :src="getProxyImageUrl(heroDetail.img)" 
            :alt="heroDetail.name" 
            @error="handleImageError"
            @load="handleImageLoad"
            crossorigin="anonymous"
            referrerpolicy="no-referrer"
          />
          <div class="image-error-placeholder" v-if="imageLoadError" style="
            display: flex;
            align-items: center;
            justify-content: center;
            height: 300px;
            background-color: rgba(255, 255, 255, 0.1);
            border: 2px dashed #666;
            color: #ff6b6b;
            font-size: 14px;
            text-align: center;
            margin-top: 8px;
          ">
            <div>
              <div>头像加载失败</div>
              <div style="font-size: 12px; margin-top: 6px; color: #999;">可能是跨域/防盗链限制</div>
              <div style="font-size: 10px; margin-top: 4px; color: #666; word-break: break-all;">
                原始URL: {{ getImageUrl(heroDetail.img) }}
              </div>
              <div style="font-size: 10px; margin-top: 2px; color: #666; word-break: break-all;">
                代理URL: {{ getProxyImageUrl(heroDetail.img) }}
              </div>
              <button 
                @click="retryLoadImage" 
                style="
                  margin-top: 8px;
                  padding: 4px 8px;
                  background-color: #409eff;
                  color: white;
                  border: none;
                  border-radius: 4px;
                  cursor: pointer;
                  font-size: 12px;
                "
              >重试加载</button>
            </div>
          </div>
        </div>
        
        <div class="hero-info">
          <h1>{{ heroDetail.name }}</h1>
          <div class="description">{{ heroDetail.description }}</div>
          
          <div class="skill-section">
            <h2>技能</h2>
            <div class="skill-info">
              <div class="skill-icon-container" v-if="heroDetail.kill_img">
                <img :src="getImageUrl(heroDetail.kill_img)" alt="技能图标" @error="handleImageError" />
              </div>
              <p>{{ heroDetail.skill }}</p>
            </div>
          </div>
        </div>
        
        <!-- 右侧大图区域 -->
        <div class="hero-large-image" v-if="heroDetail.gro_img">
          <img 
            :src="getProxyImageUrl(heroDetail.gro_img)" 
            :alt="heroDetail.name + '大图'" 
            @error="handleImageError"
            @load="handleImageLoad"
            style="display: block;"
            crossorigin="anonymous"
            referrerpolicy="no-referrer"
          />
          <!-- 图片加载失败时显示的错误提示 -->
          <div class="image-error-placeholder" v-if="imageLoadError" style="
            display: flex;
            align-items: center;
            justify-content: center;
            height: 400px;
            background-color: rgba(255, 255, 255, 0.1);
            border: 2px dashed #666;
            color: #ff6b6b;
            font-size: 16px;
            text-align: center;
          ">
            <div>
              <div>图片加载失败</div>
              <div style="font-size: 12px; margin-top: 8px; color: #999;">
                可能是跨域问题或图片服务器不可访问
              </div>
              <div style="font-size: 10px; margin-top: 4px; color: #666; word-break: break-all;">
                原始URL: {{ getImageUrl(heroDetail.gro_img) }}
              </div>
              <div style="font-size: 10px; margin-top: 2px; color: #666; word-break: break-all;">
                代理URL: {{ getProxyImageUrl(heroDetail.gro_img) }}
              </div>
              <button 
                @click="retryLoadImage" 
                style="
                  margin-top: 10px;
                  padding: 5px 10px;
                  background-color: #409eff;
                  color: white;
                  border: none;
                  border-radius: 4px;
                  cursor: pointer;
                  font-size: 12px;
                "
              >
                重试加载
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="hero-bonds">
        <h2>羁绊</h2>
        <div class="bond-list">
          <div v-for="bond in heroBonds" :key="bond.bond_id" class="bond-item">
            {{ bond.name }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElLoading } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import HeroAPI from '@/api/hero.api'

const route = useRoute()
const router = useRouter()
const heroId = ref(route.query.id)
const heroDetail = ref({})
const heroBonds = ref([])
const imageLoadError = ref(false)

// 计算背景样式，添加默认背景和错误处理
const backgroundStyle = computed(() => {
  // 检查是否有背景图片URL
  if (heroDetail.value.gro_img) {
    // 如果是相对路径，添加完整的URL前缀
    const imgUrl = getImageUrl(heroDetail.value.gro_img);
    
    return {
      backgroundImage: `url(${imgUrl})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat'
    }
  }
  
  // 如果没有背景图，使用默认的深色背景和渐变
  return {
    background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)'
  }
})

// 处理图片URL
const getImageUrl = (imgPath) => {
  if (!imgPath) return '';
  
  // 如果已经是完整的HTTP或HTTPS URL，直接返回
  if (imgPath.startsWith('http://') || imgPath.startsWith('https://')) {
    return imgPath;
  }
  
  // 如果是相对路径，添加API前缀
  if (imgPath.startsWith('/')) {
    return `http://localhost:8080${imgPath}`;
  }
  
  // 如果没有斜杠开头，添加完整路径
  return `http://localhost:8080/${imgPath}`;
}

// 创建代理图片URL来解决跨域问题
const getProxyImageUrl = (imgPath) => {
  const originalUrl = getImageUrl(imgPath);
  
  // 如果是外部URL（HTTPS且非本地），使用代理服务，处理防盗链/跨域
  if ((originalUrl.startsWith('https://') || originalUrl.startsWith('http://')) && !originalUrl.includes('localhost')) {
    return `https://images.weserv.nl/?url=${encodeURIComponent(originalUrl)}`;
  }
  
  return originalUrl;
}

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src);
  console.error('错误详情:', event);
  imageLoadError.value = true;
  // 隐藏加载失败的图片
  event.target.style.display = 'none';
}

// 处理图片加载成功
const handleImageLoad = (event) => {
  console.log('图片加载成功:', event.target.src);
  imageLoadError.value = false;
  event.target.style.display = 'block';
}

// 重试加载图片
const retryLoadImage = () => {
  console.log('重试加载图片');
  imageLoadError.value = false;
  
  // 强制重新加载图片
  const largeImg = document.querySelector('.hero-large-image img');
  const avatarImg = document.querySelector('.hero-image img');
  const targets = [largeImg, avatarImg].filter(Boolean);
  
  targets.forEach((el, idx) => {
    const original = idx === 0 ? getProxyImageUrl(heroDetail.value.gro_img) : getProxyImageUrl(heroDetail.value.img);
    el.src = '';
    setTimeout(() => {
      const hasQuery = original.includes('?');
      el.src = original + (hasQuery ? '&' : '?') + 't=' + Date.now();
    }, 100);
  });
}

// 获取英雄详情
const fetchHeroDetail = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  
  try {
    // 重置错误状态
    imageLoadError.value = false;
    
    const response = await HeroAPI.getHero(heroId.value)
    heroDetail.value = response
    
    // 调试信息
    console.log('Hero detail:', response)
    console.log('Background image URL:', response.gro_img)
    console.log('Processed gro_img URL:', getImageUrl(response.gro_img))
    
    // 检查URL格式
    if (response.gro_img) {
      const processedUrl = getImageUrl(response.gro_img);
      const proxyUrl = getProxyImageUrl(response.gro_img);
      console.log('Final image URL for gro_img:', processedUrl);
      console.log('Proxy image URL for gro_img:', proxyUrl);
      
      // 测试图片是否可以加载
      const testImg = new Image();
      testImg.onload = () => {
        console.log('gro_img 图片可以正常加载');
      };
      testImg.onerror = () => {
        console.error('gro_img 图片加载失败，URL:', proxyUrl);
        imageLoadError.value = true;
      };
      testImg.src = proxyUrl;
    }
  } catch (error) {
    console.error('获取英雄详情失败', error)
  } finally {
    loading.close()
  }
}

const fetchHeroBonds = async () => {
  try {
    const response = await HeroAPI.getHeroBonds(heroId.value)
    heroBonds.value = response
  } catch (error) {
    console.error('获取英雄羁绊失败', error)
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  fetchHeroDetail()
  fetchHeroBonds()
})
</script>

<style scoped>
.hero-detail {
  position: relative;
  min-height: 100vh;
  color: white;
  padding: 20px;
}

.hero-detail::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url('../assets/heard(2).png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  opacity: 0.3;
  z-index: -1;
}

.hero-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0.2;
  z-index: -2;
  /* 默认背景：深色渐变 */
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
}

.back-button {
  display: inline-flex;
  align-items: center;
  padding: 10px 15px;
  background: rgba(0, 163, 131, 0.8);
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 20px;
  transition: background 0.3s;
  z-index: 10;
  position: relative;
}

.back-button:hover {
  background: rgba(0, 163, 131, 1);
}

.hero-content {
  max-width: 1200px;
  margin: 0 auto;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 10px;
  padding: 30px;
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
}

.hero-main {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  align-items: flex-start;
}

.hero-image img {
  width: 300px;
  height: 300px;
  object-fit: cover;
  border: 3px solid #00a383;
  border-radius: 10px;
}

.hero-info {
  flex: 1;
  min-width: 0; /* 防止flex项目溢出 */
}

.hero-large-image {
  flex-shrink: 0;
  width: 400px;
  height: 600px;
  overflow: hidden;
  border-radius: 10px;
  border: 3px solid #00a383;
}

.hero-large-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hero-info h1 {
  font-size: 36px;
  margin-bottom: 20px;
  color: #00a383;
}

.description {
  white-space: pre-line;
  line-height: 1.6;
  margin-bottom: 25px;
}

.skill-section h2 {
  color: #00a383;
  margin-bottom: 15px;
}

.skill-info {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.skill-icon-container {
  width: 80px;
  height: 80px;
  object-fit: contain;
  flex-shrink: 0;
}

.hero-bonds h2 {
  color: #00a383;
  margin-bottom: 15px;
}

.bond-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.bond-item {
  padding: 8px 15px;
  background: rgba(0, 163, 131, 0.3);
  border: 1px solid #00a383;
  border-radius: 20px;
}

@media (max-width: 768px) {
  .hero-main {
    flex-direction: column;
  }
  
  .hero-image img {
    width: 100%;
    height: auto;
  }
  
  .hero-large-image {
    width: 100%;
    height: 400px;
    order: -1; /* 在移动端将大图移到顶部 */
  }
  
  .skill-info {
    flex-direction: column;
  }
}
</style>
